package com.chinaunicom.behavior.observer;

import java.lang.reflect.Array;
import java.util.*;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2022/8/19 10:23
 * Description: 发布者
 */
public class Publisher {
    private Map<String, ArrayList<Subscriber>> map = new HashMap<>();


    /**
     * 订阅消息
     * @param eventType
     * @param subscriber
     */
    public void subscribe(String eventType, Subscriber subscriber) {
        ArrayList<Subscriber> subscribers = map.get(eventType);
        if (subscribers == null ){
            subscribers = new ArrayList<>();
        }
        subscribers.add(subscriber);

        if ( !map.containsKey(eventType) ){
            map.put(eventType, subscribers);
        }
    }


    /**
     * 取消订阅
     * @param eventType
     * @param subscriber
     */
    public void unSubscribe(String eventType, Subscriber subscriber){
        if ( map.containsKey(eventType) ){
            List<Subscriber> subscribers = map.get(eventType);
            subscribers.remove(subscriber);
        }else {
            System.out.println("该 eventType :"+eventType +" 不存在 .........");
        }
    }
    
    
    public void notify(String eventType, String message){
        if (map.containsKey(eventType)){
            List<Subscriber> subscribers = map.get(eventType);
            subscribers.forEach(v->{
                v.update(message);
            });
        }else {
            System.out.println("该 eventType 不存在 .........");
        }
    }
}
